package com.cbs.android.function.qrcodescan;

import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.widget.CheckBox;
import android.widget.CompoundButton;

import com.cbs.android.component.application.activity.CBSActivity;
import com.cbs.android.component.toast.Toast;

import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zbar.ZBarView;

/**
 * Created by broche on 6/22/16.
 */
public class ScanActivity extends CBSActivity implements QRCodeView.Delegate {
    private QRCodeView qrCodeView;
    private CheckBox torchlightView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cbs_qrcodescan_scan);

        setResult(RESULT_CANCELED);
        qrCodeView = (ZBarView) findViewById(R.id.cbs_qrcode_scan_scan_zbar);
        qrCodeView.setDelegate(this);

        torchlightView = (CheckBox) findViewById(R.id.cbs_qrcode_scan_scan_torchlight);
        torchlightView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    qrCodeView.openFlashlight();
                } else {
                    qrCodeView.closeFlashlight();
                }
            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
        qrCodeView.startCamera();
        qrCodeView.startSpotDelay(100);
        qrCodeView.showScanRect();
    }

    @Override
    protected void onStop() {
        qrCodeView.stopSpot();
        qrCodeView.stopCamera();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        qrCodeView.onDestroy();
        super.onDestroy();
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        vibrate();
        Intent intent = new Intent();
        intent.putExtra(QRCodeScanFunction.Extras.Result, result);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        Toast.show(getResources().getString(R.string.cbs_qrcodescan_error));
    }
}
